<!DOCTYPE html>
<html>
<head>
	<title>welcome</title>
	<meta name="viewport" content='width=device-width'>
</head>
<link rel="stylesheet" type="text/css" href="/public/css/common.css">
<style type="text/css">
	.center{text-align: center;}
	.btn-group button{background:#cdcdcd;color:#333;cursor: pointer; padding:2px 5px;border:none;border-radius: 3px;}
	.btn-group button+button{margin-left:10px;}
	tr>td:first-child{width:120px;text-align: center;}
</style>
<body>
<h1 class='center'>hello Node</h1>
<div class="center"><img src='/public/img/1.png' /></div>
<button onclick='getCompany()'>获取公司</button>
<div>
	添加公司
	<input type="text" id="addName" name="">
	<div>
		<button onclick="addCompany()">确定</button>
	</div>
</div>
<table>
	<thead>
		<tr>
			<td>公司</td> <td>操作</td>
		</tr>
	</thead>
	<tbody id="list">
		<!-- <tr>
			<td>中国移动</td> <td class='btn-group'><button>修改</button> <button>删除</button></td>
		</tr> -->
	</tbody>
</table>
<div id="edit_box" style="display: none">
	公司名称 <input type="text" id="comName" name="" data-id=""> <br>
	<button onclick="editCompany()">确定</button> <button>取消</button>
</div>
<script type="text/javascript" src="/public/js/jquery.min.js"></script>
<script type="text/javascript">
	function getCompany(){
		$.get("/index/get_company",function(res){
			console.log("company",res);
			if(res.code==0){
				for(var i=0,len=res.data.length,data=res.data,html="";i<len;i++){
					html+=`<tr><td>${data[i].company}</td> <td class='btn-group' data-cid='${data[i].cpid}'><button class="edit-btn">修改</button> <button onclick='deleteCompany(${data[i].cpid})'>删除</button></td></tr>`
				}
				$("#list").html(html);
				$(".edit-btn").on("click",function(){
					var id=$(this).parent().data("cid");
					var value=$(this).parent().parent().find("td").eq(0).text()
					console.log("company id",id)
					$("#comName").data("id",id).val(value);
					$("#edit_box").show();
				})
			}
		})
	}
	getCompany()
	function editCompany(){
		var id=$("#comName").data("id");
		var val=$("#comName").val();
		if(!val){
			alert("公司名称不能为空");
			return true;
		}
		$.post("/index/edit_company",{id,val},function(res){
				if(res.code==0){
					$("#edit_box").hide();
					getCompany();

				}
		})
	}
	function deleteCompany(id){
		$.post("/index/delete_company",{id},(res)=>{
			console.log("delete",res);
			if(res.code==0)getCompany();
		})
	}
	function addCompany(){
		var value=$("#addName").val();
		if(!value){alert("请填写公司名称");return true;}
		$.get("/index/add_company",{company:value},function(res){
			if(res.code==0){
				getCompany();
			}
		})
	}
</script>
</body>
</html>